const Koa = require('koa');
const fs = require('fs');
const bodyParser = require('koa-bodyparser'); //解析POST 参数
const router = require('koa-router')(); //返回的是函数
const static = require('koa-static'); //静态
const path = require("path");

const app = new Koa();
const publicDir = path.resolve(__dirname, '../');

//默认text/plain  ctx.response.type  json,xml,html,text
//ctx.type = ctx.response.type
async function log(ctx, next) {
    // ctx.response.type = 'json';
    const start = new Date().getTime();
    await next();
    const end = new Date().getTime();
    console.log(`${ctx.method} ${ctx.path}, useTime ${end - start}ms`)
    ctx.set('X-Response-Time', `${end - start}ms`);
}


app.use(log);
app.use(static(publicDir));
app.use(bodyParser());

app.use(async (ctx, next) => { //没有next不执行，可以同步执行 !async
    if (ctx.request.path === '/index') {
        ctx.type = 'html';
        ctx.body = fs.createReadStream('./views/index.html');
        return;
    }
    await next();
});

router.get("/info", async (ctx, next) => {
    ctx.response.body = {
        "name": "huang",
        age: 15
    };
});

router.post("/info", async (ctx, next) => {
    console.log(ctx.request.body);
    ctx.response.body = {
        "name": "qian",
        age: 16
    };
});

router.get('/:user/:id', function (ctx, next) {
    console.log(ctx.params); // => {user: "huang", id: "2"}
  }); 



app.use(router.routes()); 

app.listen(3000, () => {
    console.log('server is running at http://localhost:3000');
});